#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int* createCharactersArray(char *needle, size_t nlen) // I wanted to use a hash construction but I would spend too much time for hash creation because i decided to use some characters' features
{
    int* result = (int*)malloc(sizeof(int) * 128);

    size_t i;
    for(i = 0; i < 128; i++)
	{
        *(result + i) = nlen;
    }

    for(i = 0; i < nlen - 1; i++)
	{
        *(result + (int)needle[i]) = nlen - i - 1;
    }
    return result;
}

char* loadFile(FILE* inputString, int* count)
{
	fseek(inputString, 0L, SEEK_END);
    *(count) = ftell(inputString);

    char* output = (char*) malloc(sizeof(char) * *(count));
    
    fseek(inputString, 0L, SEEK_SET);
    
	if(! fread(output, sizeof(char), *(count), inputString))
	{
		return "Null";
	}
	else
	{
		return output;
	}
}

int fileSearch(char* inputString, size_t ilen, char* needle, size_t nlen)
{
	int* searchMap = createCharactersArray(needle, nlen);

    int iter = nlen - 1,
		nCounter = iter,
        iCounter = iter,
        tempDiff = ilen - nlen;

    while (nCounter >= 0 && iter <= ilen - 1) {
        nCounter = nlen - 1;
        iCounter = iter;

        while (nCounter >= 0 && inputString[iCounter] == needle[nCounter]) {
            iCounter--;
            nCounter--;
        }
        
        iter += *(searchMap + (int)inputString[iCounter]);
    }
	
	free(searchMap);

    if (iCounter >= tempDiff) {
        return 0;
    } else {
        return 1;
    }
}

int main(int argc, char* argv[])
{
    if (!argv[1])
    {
    	printf("input file name");
        return 1;
	}
	
	FILE *fp = fopen(argv[1], "r");
    
    if(!fp)
	{
        printf("Make sure existence of %s is exist", argv[1]);
        return 2;
    }
    
	char* data;
	int length;
    
    data = loadFile(fp, &length);
    
    if (!strcmp(data, "Null"))
    {
    	printf("Data access problems!");
    	return 3;
	}

    char lookupString[50]; // I think 50 characters enough for a word
    
    gets(lookupString);

    while(strcmp(lookupString, "exit"))
	{
        if(fileSearch(data, length, lookupString, strlen(lookupString)))
        {
            printf("YES\n");
        }
		else
		{
            printf("NO\n");
        }
        gets(lookupString);
    }

    free(data);
    fclose(fp);
    return 0;
}
